package com.waimai1.waimai.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.waimai1.waimai.entity.MyOrder;
import com.waimai1.waimai.service.MyOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;
import java.util.UUID;
@Slf4j
@Component
public class ListenCloseOrder {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MyOrderService orderService;
    /**
     * 监听延迟消息
     */
    @Scheduled(cron = "0/2 * * * * ?")
    public void listenDelayLoop() {
        // 获取一个到点的消息
        Set<String> set = redisTemplate.opsForZSet().rangeByScore("cancelOrder", 0, System.currentTimeMillis(), 0, 1);
        // 如果没有，就等等
        if (set.isEmpty()) {
            // 继续执行
            return;
        }
        // 获取具体消息的key
        String tradeNo =set.iterator().next();

        // 删除成功
        if (redisTemplate.opsForZSet().remove("cancelOrder", tradeNo) > 0) {
            // 业务
            log.info("关单"+tradeNo);
            LambdaQueryWrapper<MyOrder> orderLambdaQueryWrapper=new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(MyOrder::getOutTradeNo,tradeNo);
            MyOrder order=orderService.getOne(orderLambdaQueryWrapper);
//            超时如果等待付款则取消订单
            if(order.getStatus().equals(Utils.STATUS_WAIT_PAY)){
                order.setStatus(Utils.STATUS_CANCEL);
                orderService.update(order,orderLambdaQueryWrapper);
            }
//            如果是秒杀单还要把redis库存加回去，把他从购买表中删掉
            if ("秒杀".equals(order.getRemark())) {
                redisTemplate.opsForValue().increment(order.getAcid()+":P" + order.getRestaurantId());
                redisTemplate.opsForSet().remove(order.getAcid()+":U" + order.getRestaurantId(),order.getOpenid());
            }
        }
    }
}
